import router from "@/router/index";
import setting from "./setting";
import nprogress from "nprogress";
import "nprogress/nprogress.css"
nprogress.configure({ showSpinner: false });

import pinia from "./store/index"
import useUserStore from "./store/modules/user";
// 在组件的外部，需要先有大仓库，才可以获取小仓库
// 所以需先引入pinia
let userStore = useUserStore(pinia);

router.beforeEach(async(to,from,next)=>{
    // document.title=setting.title +'--'+ to.meta.title;
    document.title=`${setting.title} -- ${to.meta.title}`;
    nprogress.start();

    let token = userStore.token;
    let username = userStore.username;
    if(token){
        if(to.path == '/login'){
            next({path:'/'})
        }else{
            if(username){
                next()
            }else{
                try {
                    await userStore.userInfo();
                    next();
                } catch (error) { 
                    //获取用户信息失败，退出登陆
                    userStore.userLogout();
                    next({path:'/login',query:{redirect:to.path}});
                }
               
            }
        }
    }else{
        if(to.path == '/login'){
            next()
        }else{
            next({path:'/login',query:{redirect:to.path}})
        }
    }
})

router.afterEach(()=>{
    nprogress.done();
})

//进度条 https://www.npmjs.com/package/nprogress
